﻿CREATE PROCEDURE [audit].[InitialiseTrace]
@TraceName NVARCHAR (256), @TraceID INT OUTPUT
AS
BEGIN
	SET NOCOUNT ON

	DECLARE @RC int, @ERROR int
	SET @RC = 0
	SET @ERROR = 0
	
	IF(audit.IsTraceActive(@TraceName) = 1)
		BEGIN
			RAISERROR('The trace (%s) already exists.',16,1,@TraceName)
			SET @ERROR = @@ERROR
			GOTO ERROR_HANDLER
		END

	DECLARE @FilePath nvarchar(2000)
	SET @FilePath = config.GetInstanceSetting(N'TraceFileFolder')
	IF(@FilePath IS NULL)
		BEGIN
			RAISERROR('Invalid trace file folder.',16,1)
			SET @ERROR = @@ERROR
			GOTO ERROR_HANDLER
		END

	SET @FilePath = @FilePath + N'\' + @TraceName + N'_' +
		REPLACE(
			REPLACE(
				REPLACE(
					CONVERT(nvarchar,GETDATE(),20)
				,N'-',N'')
			,N' ',N'')
		,N':',N'')

	EXEC @RC = master.dbo.sp_trace_create @TraceID = @TraceID OUTPUT,
		@options = 2, --TRACE_FILE_ROLLOVER
		@tracefile = @FilePath,
		@maxfilesize = NULL,
		@stoptime = NULL
	SET @ERROR = @@ERROR
	IF(@ERROR <> 0)
	OR(@RC <> 0)
		GOTO ERROR_HANDLER

	PRINT 'Trace Initialised'
	GOTO EXIT_PROC

ERROR_HANDLER:
	IF(@RC <> 0)
		BEGIN
			DECLARE @ERROR_MESSAGE nvarchar(256)
			SET @ERROR_MESSAGE = audit.GetTraceReturnCodeValue(@RC)
			RAISERROR(@ERROR_MESSAGE,16,1)
		END
	ELSE
		SET @RC = @ERROR

	RAISERROR('Failed initialise trace',16,1)

EXIT_PROC:
	RETURN(@RC)
END